package com.skivingcloud.report.ureport.provider;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bstek.ureport.provider.report.ReportFile;
import com.bstek.ureport.provider.report.ReportProvider;
import com.skivingcloud.common.utils.UuidUtil;
import com.skivingcloud.report.ureport.entity.UreportFileTbl;
import com.skivingcloud.report.ureport.mapper.UreportFileTblMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 数据库 报表存储
 * 
 * @author hushouquan
 * @version 2018年5月9日
 *
 */
@Component
// 该注解可以利用其 prefix属性值 + 类的属性名 在yml中配置属性值
@ConfigurationProperties(prefix = "ureport.db.provider")
public class DbProvider implements ReportProvider{

    private static final String NAME = "db-provider";

    // 特定前缀，ureport底层会调用 getPrefix 方法来获取报表操作的Provier类
    @Value("${ureport.db.provider.prefix:db}")
    private String prefix;

    // 是否禁用
    @Value("${ureport.db.provider.disabled:false}")
    private boolean disabled;
    
    @Autowired
    private UreportFileTblMapper ureportFileTblMapper;
    
    @Override
    public InputStream loadReport(String file) {
        QueryWrapper<UreportFileTbl> queryWrapper = new QueryWrapper<UreportFileTbl>();
        queryWrapper.eq("name", getCorrectName(file));
        List<UreportFileTbl> list = ureportFileTblMapper.selectList(queryWrapper);
        UreportFileTbl ureportFileEntity = list.isEmpty() ? null : list.get(0);
        String content = ureportFileEntity.getContent();
        try {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes("utf-8"));
            return inputStream;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void deleteReport(String file) {
        QueryWrapper<UreportFileTbl> queryWrapper = new QueryWrapper<UreportFileTbl>();
        queryWrapper.eq("name", getCorrectName(file));
        ureportFileTblMapper.delete(queryWrapper);
    }

    @Override
    public List<ReportFile> getReportFiles() {
        QueryWrapper<UreportFileTbl> queryWrapper = new QueryWrapper<UreportFileTbl>();
        List<UreportFileTbl> list = ureportFileTblMapper.selectList(queryWrapper);
        List<ReportFile> reportList = new ArrayList<ReportFile>();
        for (UreportFileTbl ureportFileEntity : list) {
            reportList.add(new ReportFile(ureportFileEntity.getName(), Date.from(
                    ureportFileEntity.getUpdateTime().atZone(ZoneId.systemDefault()).toInstant())));
        }
        return reportList;
    }

    @Override
    public void saveReport(String file, String content) {
        file = getCorrectName(file);
        QueryWrapper<UreportFileTbl> queryWrapper = new QueryWrapper<UreportFileTbl>();
        queryWrapper.eq("name", getCorrectName(file));
        List<UreportFileTbl> list = ureportFileTblMapper.selectList(queryWrapper);
        UreportFileTbl ureportFileEntity = list.isEmpty() ? null : list.get(0);
        LocalDateTime currentDate = LocalDateTime.now();
        if (ureportFileEntity == null) {
            ureportFileEntity = new UreportFileTbl();
            ureportFileEntity.setId(UuidUtil.get32UUID());
            ureportFileEntity.setName(file);
            ureportFileEntity.setContent(content);
            ureportFileEntity.setCreateTime(currentDate);
            ureportFileEntity.setUpdateTime(currentDate);
            ureportFileTblMapper.insert(ureportFileEntity);
        } else {
            ureportFileEntity.setContent(content);
            ureportFileEntity.setUpdateTime(currentDate);
            ureportFileTblMapper.updateById(ureportFileEntity);
        }
    }

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public boolean disabled() {
        return disabled;
    }

    @Override
    public String getPrefix() {
        return prefix;
    }
    
    /**
     * 获取没有前缀的文件名
     * 
     * @param name
     * @return
     */
    private String getCorrectName(String name) {
        if (name.startsWith(getPrefix())) {
            name = name.substring(getPrefix().length(), name.length());
        }
        return name;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public boolean isDisabled() {
        return disabled;
    }

    public void setDisabled(boolean disabled) {
        this.disabled = disabled;
    }
}